package com.gz.purchase.library.listener;

import com.gz.purchase.library.pojo.ProductInfo;
import com.gz.purchase.library.pojo.UserInfo;
import com.gz.purchase.library.util.Constants;
import com.gz.purchase.library.util.CrashHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * author wanner1991
 * 主页获取订单监听器
 */
public abstract class GetMainProductsListener extends BaseListener {
    private String TAG = GetMainProductsListener.class.getSimpleName();

    public GetMainProductsListener(RequestCode requestCode) {
        super(requestCode);
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        try {
            int status = response.getInt(Constants.REQ_STATUS);
            String msg = response.getString(Constants.REQ_MSG);
            CrashHandler.i(TAG,response.toString());
            CrashHandler.i(TAG, "获取首页商品status = " + status);
            CrashHandler.i(TAG, "获取首页商品msg = " + msg);

            switch(status){
                case Constants.REQ_OK:
                    JSONObject jsonobject = response.getJSONObject(Constants.REQ_RESULT);
                    onResponseSuccess(ProductInfo.parse(jsonobject.getJSONArray(Constants.REQ_PRODUCTS)));
                    break;
                case Constants.REQ_NO_DATA:
                    onNoMoreData();
                    break;
                case Constants.REQ_DATA_ERROR:
                    //存在未被关联的基础商品，请联系相关人员维护
                    onDataError(response.getString(Constants.REQ_RESULT));
                    break;
                default:
                    onResponseFailed();
            }

        } catch (JSONException e) {
            onFailure(statusCode, headers, e, new JSONObject());
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers,
                          Throwable throwable, JSONObject errorResponse) {
        CrashHandler.e(throwable);
        onResponseFailed();
    }

    @Override
    public void onOffline() {

    }

    public abstract void onResponseSuccess(List<ProductInfo> products);
    public abstract void onDataError(String shop_name);
}
